package com.wlf.server.task;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlf.server.common.em.Const;
import com.wlf.server.common.entity.ScheduleJob;
import com.wlf.server.common.entity.ScheduleLog;
import com.wlf.server.common.quartz.base.BaseQuartz;
import com.wlf.server.common.service.ScheduleJobService;
import com.wlf.server.common.service.ScheduleLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 功能描述: 清理定时任务日志
 *
 * @author wlf 2023/9/23 11:13
 */
@Slf4j
@Component(Const.TaskBeanKey + "cleanTaskLog")
public class CleanTaskLog implements BaseQuartz {
    @Resource
    private ScheduleLogService logService;

    @Resource
    private ScheduleJobService jobService;

    /**
     * 清除任务日志
     */
    @Override
    public void run(String params) {
        // 执行十次，
        for (int i = 0; i < 10; i++) {
            for (ScheduleJob job : jobService.list()) {
                long count = logService.lambdaQuery().eq(ScheduleLog::getJobId, job.getId()).count();
                if (count > 100000) {
                    Page<ScheduleLog> page = logService.lambdaQuery().eq(ScheduleLog::getJobId, job.getId())
                            .orderByDesc(ScheduleLog::getId).page(Page.of(1, 1000));
                    logService.removeBatchByIds(page.getRecords().stream().map(ScheduleLog::getId).toList());
                }
            }
        }
    }
}
